package server.communication.listeners;

import server.Server;
import server.threads.ServerCommunicator;
import message.Message;
import message.RestartServerRequestMessage;
import message.RestartServerResponseMessage;
import message.ServerMessageWrapper;
import communication.MessageListener;
import communication.MessageReceivedEvent;

public class RestartListener implements MessageListener
{
	private final Server server;
	private final ServerCommunicator communicator;
	
	public RestartListener(ServerCommunicator communicator, Server server)
	{
		this.communicator = communicator;
		this.server = server;
	}
	
	@Override
	public void messageRecieved(MessageReceivedEvent e)
	{
		ServerMessageWrapper message = ((ServerMessageWrapper) e.getMessage());
		RestartServerResponseMessage response = new RestartServerResponseMessage();
		
		server.restart();
		
		response.setRestarting(true);
		
		communicator.sendMessage(message.connectionId, response);
	}
	@Override
	public boolean acceptsMessage(Message message)
	{
		if (message.getClass().equals(ServerMessageWrapper.class))
			message = ((ServerMessageWrapper) message).internalMessage;
		
		return message.getClass().equals(RestartServerRequestMessage.class);
	}
}
